package org.hxzon.emailblog.blog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class BlogFile {
    private boolean useAttachment;
    private String title;
    private String contentOrig;
    private List<BlogImage> images;
    private String contentEmail;

    public String toString() {
        return this.title;
    }

    public String getContentEmail() {
        if (contentEmail == null) {
            modifyContent();
        }
        return contentEmail;
    }

    private void modifyContent() {
        images = new ArrayList<BlogImage>();
        if (!useAttachment) {
            contentEmail = contentOrig;
            return;
        }
        Document doc = Jsoup.parseBodyFragment(contentOrig);
        Element bodyElement = doc.body();
        // update image src
        Elements imageElements = bodyElement.getElementsByTag("img");
        BlogImage imageInfo;
        Map<String, BlogImage> cache = new HashMap<String, BlogImage>();
        int i = 0;
        for (Element imageElement : imageElements) {

            String imageSrc = imageElement.attr("src");
            imageInfo = cache.get(imageSrc);
            if (imageInfo == null) {
                imageInfo = new BlogImage();
                imageInfo.setOrigSrc(imageSrc);
                imageInfo.setCid("image" + i);
                i++;
                cache.put(imageSrc, imageInfo);
            }
            imageElement.attr("src", "cid:" + imageInfo.getCid());// modify src
            imageElement.after("<p class='origImg'>" + imageInfo.getOrigSrc() + "</p>");
            // backup imageInfo for write imageInfo
            images.add(imageInfo);
        }
        // after change image src
        contentEmail = bodyElement.html();
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContentOrig() {
        return contentOrig;
    }

    public void setContentOrigl(String contentOrig) {
        this.contentOrig = contentOrig;
    }

    public List<BlogImage> getImages() {
        return images;
    }

    public boolean isUseAttachment() {
        return useAttachment;
    }

    public void setUseAttachment(boolean useAttachment) {
        this.useAttachment = useAttachment;
    }

}
